import koaRouter from 'koa-router'
import connection from '../config/mysqlConfig'
import jwt from 'jsonwebtoken'
import  config from '../config/appConfig'
const router = koaRouter()
router.post('/login', async (ctx) => {
    try {
        const {
            name,
            password
        } = ctx.request.body
        const result = await new Promise((resolve, reject) => {
            connection.query('select * from users where name=? and password=?', [name, password], (err, results) => {
                if (err) reject(err)
                resolve(results)
            })
        })
        if (result.length > 0) {
            // 生成token
            let token = jwt.sign({
                    name // 被加密的数据
                }, config.secret, // 秘钥
                {
                    expiresIn: '10h'
                })
            ctx.body = {
                code: 1,
                msg: '登陆成功',
                token
            }
        } else {
            ctx.body = {
                code: 0,
                msg: '登陆失败'
            }
        }
    } catch (e) {
        ctx.body = {
            code: 0,
            error: e.message
        }
    }
})

router.post('/register', async (ctx) => {
    try {
        const {
            name,
            password
        } = ctx.request.body
        // 存入数据库
        const result = await new Promise((resolve, reject) => {
            connection.query('select * from users where name=?', name, (err, results) => {
                if (err) reject(err)
                resolve(results)
            })
        })
        if (result.length > 0) {
            ctx.body = {
                code: 0,
                msg: '用户名已被注册，请重新注册'
            }
        } else {
            await new Promise((resolve, reject) => {
                connection.query('insert into users set ?', {
                    name,
                    password
                }, (err) => {
                    if (err) reject(err)
                    resolve()
                })
            })
            ctx.body = {
                code: 1,
                msg: '注册成功'
            }
        }
    } catch (e) {
        ctx.body = {
            code: 0,
            error: e.message
        }
    }
})

export default router